//
//  ZZLCRegisterVC.m
//  ZZLC
//
//  Created by 杨春至 on 2017/12/14.
//  Copyright © 2017年 ZhongZeng. All rights reserved.
//

#import "ZZLCRegisterVC.h"
#import "ZZHelper.h"
#import "ZZLSetingPWDVC.h"
#import "ZZCCProtocolViewController.h"
#import "PersonForgetLogin.h"
#import "PersonForgetTrade.h"
@interface ZZLCRegisterVC ()<UITextFieldDelegate>
{
    BOOL _timeStart;
}
@end

@implementation ZZLCRegisterVC
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.navigationController.viewControllers.count<=1) {
        [self configureNav];
    }
}
- (void)configureNav
{
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:UIImageMake(@"logBack") style:UIBarButtonItemStyleDone target:self action:@selector(leftVCShow)];
    
    self.navigationItem.leftBarButtonItem = leftItem;

}
#pragma mark ---
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSString *str = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (str.length>11) {
        return NO;
    }
    return YES;
}
- (void)leftVCShow
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewDidLoad {
     K_WS(weakSelf);
    [super viewDidLoad];
    _inputPhoneTF.delegate = self;
    switch (self.getValidationCode) {
        case GetValidationCodeFormRegister:
            {
                self.title = @"注册";
                self.indicationView.hidden = false;
            }
            break;
        case GetValidationCodeFormLoginPWD:
        {
            self.title = @"忘记登录密码";
            self.indicationView.hidden = YES;
        }
            break;
        case GetValidationCodeFormTradePWD:
        {
            self.title = @"忘记交易密码";
            self.indicationView.hidden = YES;
        }
            break;
            
        default:
            break;
    }
    [self.isAgreeBtn setImage:Image(@"register_unAgree") forState:UIControlStateNormal];
    [self.isAgreeBtn setImage:Image(@"register_agree") forState:UIControlStateSelected];
    self.isAgreeBtn.selected = YES;
    [self.isAgreeBtn addTarget:self action:@selector(isAgreeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.getcodeBtn bk_whenTapped:^{
        if ([self checkTelephoneValid:self.inputPhoneTF.text] ) {
               [weakSelf getCodeNetWorking];
        }
        else
        {
            [QMUITips showWithText:@"请输入有效的手机号码" inView:self.view hideAfterDelay:1.8];
        }
    }];
    [self.nextStepBtn bk_whenTapped:^{
        if ([self checkTelephoneValid:self.inputPhoneTF.text]&& self.vadidateCodeTF.text.length&&self.isAgreeBtn.selected) {
            [weakSelf validateNetworking];
        }
        else
        {
            if (![self checkTelephoneValid:self.inputPhoneTF.text]|| !self.vadidateCodeTF.text.length) {
                [QMUITips showWithText:@"请输入有效的手机号码和正确的验证码" inView:self.view hideAfterDelay:1.8];
                return ;
            }
            if ([self checkTelephoneValid:self.inputPhoneTF.text]&& self.vadidateCodeTF.text.length) {
                [QMUITips showWithText:@"请同意并阅读《中增理财注册协议》" inView:self.view hideAfterDelay:1.8];
            return;
            }
        }
    }];
    [self.protocolLabel bk_whenTapped:^{
        ZZCCProtocolViewController *protocolVC = [[ZZCCProtocolViewController alloc]init];
        [self.navigationController pushViewController:protocolVC animated:YES];
    }];
    // Do any additional setup after loading the view from its nib.
}
#pragma mark 同意协议
- (void)isAgreeAction:(UIButton *)sender
{
    sender.selected = !sender.selected;
}
#pragma mark 网络请求
- (void)getCodeNetWorking
{

    [NetWorkingManager postWithRequestUrl:@"findPwdSendYzm" AndParameters:@{@"parameters":[@{@"username":self.inputPhoneTF.text,@"type":[NSString stringWithFormat:@"%lu",(unsigned long)self.getValidationCode],@"imageCode":@"",@"phoneId":[ZZHelper deviceIPAdress],@"uCode":[ZZHelper ucode]} DataTOjsonStringAndAddVersion]} AndRequestBlock:^(NSDictionary *responseObject) {
        {
       
            [QMUITips showSucceed:@"获取验证码成功" inView:self.view hideAfterDelay:1.2];
            _timeStart = YES;
            NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
        }
    } FailBlock:^(NSDictionary *errDic) {
   
            [QMUITips showError:errDic[@"errorMsg"] inView:self.view hideAfterDelay:1.2];
    }ShowTips:NO];
}

- (void)validateNetworking
{

                K_WS(weakSelf);
                [NetWorkingManager postWithRequestUrl:@"findPwdYzmIsRight" AndParameters:@{@"parameters":[@{@"username":self.inputPhoneTF.text,@"yzm":self.vadidateCodeTF.text,@"type":[NSString stringWithFormat:@"%lu",(unsigned long)self.getValidationCode],@"phoneId":[ZZHelper deviceIPAdress]} DataTOjsonStringAndAddVersion]} AndRequestBlock:^(NSDictionary *responseObject) {
                    NSString *messageStr = responseObject[@"end"];

                        if ([messageStr isEqualToString:@"ok"]) {

                            switch (self.getValidationCode) {
                                case GetValidationCodeFormRegister:
                                {
                                    ZZLSetingPWDVC *setingVC = [[ZZLSetingPWDVC alloc]initWithNibName:@"ZZLSetingPWDVC" bundle:nil];
                                    setingVC.fromWhere = REGISTERVC;
                                    setingVC.phoneStr = weakSelf.inputPhoneTF.text;
                                    [weakSelf.navigationController pushViewController:setingVC animated:YES];
                                }
                                    break;
                                case GetValidationCodeFormLoginPWD:
                                {
                                    PersonForgetLogin *setingVC = [[PersonForgetLogin alloc]initWithNibName:@"PersonForgetLogin" bundle:nil];
                                    setingVC.fromWhere = FORGETVC;
                                    setingVC.phoneStr = weakSelf.inputPhoneTF.text;
                                    [weakSelf.navigationController pushViewController:setingVC animated:YES];
                                }
                                    break;
                                case GetValidationCodeFormTradePWD:
                                {
                                    PersonForgetTrade *setingVC = [[PersonForgetTrade alloc]initWithNibName:@"PersonForgetTrade" bundle:nil];
                                    setingVC.fromWhere = TRADEPWDTVC;
                                    setingVC.phoneStr = weakSelf.inputPhoneTF.text;
                                    [weakSelf.navigationController pushViewController:setingVC animated:YES];
                                }
                                    break;
                                default:
                                    break;
                            }
                            //todo
                        }

                } FailBlock:^(NSDictionary *errDic) {
                    
                }];
}
- (void)timerFireMethod:(NSTimer *)theTimer
{
    NSCalendar *cal = [NSCalendar currentCalendar];//定义一个NSCalendar对象
    NSDateComponents *endTime = [[NSDateComponents alloc] init];    //初始化目标时间...
    NSDate *today = [NSDate date];    //得到当前时间
    
    NSDate *date = [NSDate dateWithTimeInterval:60 sinceDate:today];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:date];
    
    static int year;
    static int month;
    static int day;
    static int hour;
    static int minute;
    static int second;
    if(_timeStart) {//从NSDate中取出年月日，时分秒，但是只能取一次
        year = [[dateString substringWithRange:NSMakeRange(0, 4)] intValue];
        month = [[dateString substringWithRange:NSMakeRange(5, 2)] intValue];
        day = [[dateString substringWithRange:NSMakeRange(8, 2)] intValue];
        hour = [[dateString substringWithRange:NSMakeRange(11, 2)] intValue];
        minute = [[dateString substringWithRange:NSMakeRange(14, 2)] intValue];
        second = [[dateString substringWithRange:NSMakeRange(17, 2)] intValue];
        _timeStart= NO;
    }
    
    [endTime setYear:year];
    [endTime setMonth:month];
    [endTime setDay:day];
    [endTime setHour:hour];
    [endTime setMinute:minute];
    [endTime setSecond:second];
    NSDate *todate = [cal dateFromComponents:endTime]; //把目标时间装载入date
    //    [endTime release];
    
    //用来得到具体的时差，是为了统一成北京时间
    unsigned int unitFlags = NSCalendarUnitYear| NSCalendarUnitMonth| NSCalendarUnitDay| NSCalendarUnitHour| NSCalendarUnitMinute| NSCalendarUnitSecond;
    NSDateComponents *d = [cal components:unitFlags fromDate:today toDate:todate options:0];
    
    NSString *fen = [NSString stringWithFormat:@"%ld", (long)[d minute]];
    
    if([d minute] < 10) {
        fen = [NSString stringWithFormat:@"0%ld",(long)[d minute]];
        
    }
    NSString *miao = [NSString stringWithFormat:@"%ld", (long)[d second]];
    NSLog(@"%@",miao);
    if([d second] < 10) {
        miao = [NSString stringWithFormat:@"0%ld",(long)[d second]];
    }
    
    if([d second] > 0) {
        self.getcodeBtn.enabled = NO;
        [self.getcodeBtn setTitle:[NSString stringWithFormat:@"重新发送(%@)",miao] forState:UIControlStateDisabled];
//        self.getcodeBtn.backgroundColor = [UIColor grayColor];
//        倒计时的颜色
//        [self.getcodeBtn setTitleColor:[UIColor colorWithRed:29/256.0 green:174/256.0 blue:253/256.0 alpha:1] forState:UIControlStateNormal];
        
    }else if([d second] <= 0) {

        [self.getcodeBtn setTitle:@"获取验证码" forState:UIControlStateDisabled];
        //        执行完成的颜色
//        [self.getcodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        self.getcodeBtn.backgroundColor = [UIColor colorWithRed:29/256.0 green:174/256.0 blue:253/256.0 alpha:1];
        self.getcodeBtn.enabled = YES;
        
        [theTimer invalidate];
    }
}

/**
 *  检验手机号码有效性
 */
- (BOOL)checkTelephoneValid:(NSString *)mobile{
    NSString *mobileRegex = @"^((13[0-9])|(147)|(17[0-9])|(15[^4,\\D])|(18[^4]))\\d{8}$";
    NSPredicate *mobileTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",mobileRegex];
    return [mobileTest evaluateWithObject:mobile];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
